import { _decorator, Component, Node, Sprite, UITransform, Animation, AnimationClip, BoxCollider2D, RigidBody2D, ERigidBody2DType, Size } from 'cc';
import DataManager from '../Runtime/DataManager';
import { createUINode, getFrameAsset } from '../utils';
import { GamePlayer } from '../Role/GamePlayer';
const { ccclass, property } = _decorator;
// 地刺
@ccclass('LurkerManager')
export class LurkerManager extends Component {
    status: number = 0  //0 正常，1 碰到死亡
    nodeName: string
    touchNode: Array<Node> = [] //踩到的角色
    init(name: string, touch: Boolean = false) {
        let luker_clip=DataManager.Instance.luker_clip
        const { width, position } = DataManager.Instance
        const tile = createUINode('children_' + name)
        this.nodeName = name
        tile.setPosition(0, -30)
        tile.setParent(this.node)
        const rigid2D = tile.addComponent(RigidBody2D)
        rigid2D.type = ERigidBody2DType.Dynamic
        const boxCollider2D = tile.addComponent(BoxCollider2D)
        boxCollider2D.sensor = true
        rigid2D.gravityScale = 0
        const transform = tile.getComponent(UITransform)
        if (name.includes("Touch")) {
            boxCollider2D.size = new Size(width - 6, position - 6)
        } else {
            boxCollider2D.size = new Size(width * 0.8, position * 0.8)
        }
        transform.setContentSize(width - 2, position - 2)
        let sprite = tile.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.mapAssets, '253.png').spriteFrame
        const animation = tile.addComponent(Animation)
        if (touch) {
            luker_clip.wrapMode = AnimationClip.WrapMode.Default
            animation.defaultClip = luker_clip
            animation.pause()
        } else {
            animation.defaultClip = luker_clip
            animation.play()
        }
    }

    update(deltaTime: number) {
        let animation = this.node.getChildByName('children_' + this.nodeName).getComponent(Animation)
        const animationState = animation.getState('luker');
        let current = Number(animationState.current.toFixed(1))
        let duration = animationState.duration
        let length = DataManager.Instance.luker_frame.length
        let deathStartTime = (duration / length) * 30
        let deathEndTime = (duration / length) * 55
        if (current == duration || current == 0) {
            this.status = 0
        }else{
            this.status = 1
        }
        if (current >= deathStartTime && current <= deathEndTime) {
            if (this.touchNode.length > 0) {
                this.touchNode.forEach((item)=>{
                    item.getComponent(GamePlayer).characterDeath()
                })
                this.touchNode=[]
            }
        } else {

        }
    }
}


